package ru.sgu.diploma.practic.service.impl;

import org.apache.log4j.Logger;
import ru.sgu.diploma.practic.domain.model.AutomatResult;
import ru.sgu.diploma.practic.domain.model.Point;
import ru.sgu.diploma.practic.errors.NextLetterException;
import ru.sgu.diploma.practic.service.AutomatResultConverter;

import java.util.LinkedList;
import java.util.List;

/**
 * User: datmakin
 * Date: 14.03.11
 * Email: atmakin.dv@gmail.com
 */
public class AutomatResultConverterImpl implements AutomatResultConverter {

    Logger logger = Logger.getLogger(AutomatResultConverterImpl.class);

    public List<Point> convert(List<AutomatResult> automatResults, String[] alphabet) throws NextLetterException {
        for (AutomatResult automatResult : automatResults) {
            automatResult.setInput(convert(automatResult.getInputStr(), alphabet));
            automatResult.setOutput(convert(automatResult.getOuputStr(), alphabet));
        }

        return normilize(automatResults);
    }

    private List<Point> normilize(List<AutomatResult> automatResults) {
        List<Point> result = new LinkedList<Point>();
        for (AutomatResult automatResult : automatResults) {
            Integer input = new Long(Math.round(automatResult.getInput()*100)).intValue();
            Integer output = new Long(Math.round(automatResult.getOutput()*100)).intValue();
            logger.debug("get new point: ("+input+","+output+")");
            result.add(new Point(input, output));
        }

        return result;
    }

    private Double convert(String vector[], String[] alphabet) throws NextLetterException {

        Double result = 0.0;

        for (int i = 0; i < vector.length; i++) {
            if (i == 0)
                result += getNumber(vector[i], alphabet);
            else
                result += getNumber(vector[i], alphabet) / alphabet.length * i;
        }

        return result;
    }

    private Double getNumber(String letter, String[] alphabet) throws NextLetterException {

        for (int i = 0; i < alphabet.length; i++)
            if (alphabet[i].equals(letter))
                return new Double(i);

        throw new NextLetterException("letter not found");
    }
}
